﻿using NSoup.Nodes;
using NSoup.Select;
using QD.Snapshot.Core.Config;
using QD.Utill;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Windows.Forms;

namespace QD.Snapshot.Core.BLL
{
    public class Search_Weixin : SearchBase
    {
        static string SNUID = "";
        static string SUID = "";
        static string SUV = "";
        static int dbCount = 0;     //数据库查询次数
        static bool IsFristRun = true;   //首次进入给SNUID和SUV赋值

        public Search_Weixin(TextBox textBox, int SleepTime)
        {
            this.textBox = textBox;
            this.SleepTime = SleepTime;
            this.copyform = "5";        //微信搜狗搜索引擎
            Echo("微信搜狗截图已启动");
        }

        static Model.TaskModel_360 taskModel = new Model.TaskModel_360();
        static HttpRequest Http = new HttpRequest();
        public override void Search(string keyword, Model.Product product, Model.WebSite company)
        {
            Thread.Sleep(SleepTime);
            InitParam();

            
            Http.ClearCookie();
            Http.AddCookie("SNUID", SNUID, "sogou.com", DateTime.Now.AddYears(1));
            Http.AddCookie("SUID", SUID, "weixin.sogou.com", DateTime.Now.AddYears(1));
            Http.AddCookie("SUV", SUV, "sogou.com", DateTime.Now.AddYears(1));


            string html = string.Empty;
            string msg = string.Empty;
            msg = Http.Requset(string.Format(Engine.URL_WX, keyword), out html);

            IsCode_WX = CheckCode(html);   //是否出现验证码

            if (IsCode_WX)
            {
                EchoLog("code", "微信搜狗出现验证码");
                Thread.Sleep(1000);
            }
            else if (msg.Length > 1)
            {
                Echo(string.Format("搜索失败: {0}", msg));
            }
            else
            {
                Echo(string.Format("搜索 {0}", keyword));

                taskModel.itemid = product.itemid;
                taskModel.keyword = keyword;
                taskModel.company = company;
                taskModel.html = html;

                NumHelper.Instance.SetNumWeixin(1);    //统计搜索速度

                ThreadPool.QueueUserWorkItem(new WaitCallback(CheckOrAdd), taskModel);
            }

        }

        void CheckOrAdd(object obj)
        {
            Model.TaskModel_360 model = obj as Model.TaskModel_360;

            CheckOrAdd(model.html, model.keyword, model.itemid, model.company);

            model = null;
        }

        void CheckOrAdd(string html, string keyword, int itemid, Model.WebSite company)
        {
            html = Regex.Replace(html, "<!--([\\s\\S].*?)-->", "");
            NSoup.Nodes.Document doc = NSoup.NSoupClient.Parse(html);
            Regex r1 = new Regex(FixRegex(company.ShortName), RegexOptions.IgnoreCase);
            Regex r2 = new Regex(FixRegex(keyword), RegexOptions.IgnoreCase);
            Regex SiteName = new Regex(FixRegex(company.SiteName), RegexOptions.IgnoreCase);
            Regex Cellphone = new Regex(FixRegex(company.Cellphone), RegexOptions.IgnoreCase);
            Regex phone = new Regex(FixRegex(company.Phone), RegexOptions.IgnoreCase);

            
            CheckOrAdd(doc, r1, SiteName, Cellphone, phone, itemid, company.UserID, keyword);
        }

        void CheckOrAdd(Document doc, Regex r1, Regex SiteName, Regex Cellphone, Regex phone, int itemid, int userid, string keyword, int page = 1)
        {
            NSoup.Nodes.Element parent = doc.GetElementById("main");
            if (parent == null) return;

            NSoup.Select.Elements result = parent.Select(".news-list"); 
            if (result == null) return;

            HideElement(doc.GetElementById("right"));         //清空右侧的图片和排名    
            HideElementList(parent.GetElementsByClass("img-box"));      //清空每行的右侧图片
            HideElementList(parent.GetElementsByClass("img-d"));         //清空每行图片列表


            int index = 0;
            bool isFirst = true;
            string nums_html = "";
            foreach (Element ele in result)
            {  
                index++;
                if (r1.IsMatch(ele.Text()) || CheckShortNameList(ele.Text()) || CheckQJY(ele.Text(), SiteName, Cellphone, phone))
                {
                    //string index_key = GetMd5(ele.GetElementsByTag("h3").Text); //第几行的key,更新时，用来确定更新哪一行
                    //string platform = GetPlatform(ele.Text());                  //上词的平台
                    string index_key = "0";
                    string platform = "0";

                    if (isFirst)
                    {
                        RemoveAttr(result);
                        nums_html = "<div class='mun'>" + parent.Select(".mun").Text + "</div>";
                        isFirst = false;
                    }

                    //添加成功记录
                    AddSnap(page, userid, itemid, index, keyword, result.OuterHtml() + nums_html, platform, index_key);
                }
            }
        }

        protected override void RemoveAttr(Elements result)
        {
            Elements div = result.Select("div");
            div.RemoveAttr("id");
            div.RemoveAttr("s-p");
            div.RemoveAttr("t");
            div.RemoveClass("img-box");

            Elements p = result.Select("p");
            p.RemoveAttr("txt-info");
            p.RemoveAttr("id");

            Elements ele = result.Select("a");
            ele.Attr("href", "#");
            ele.RemoveAttr("data-share");
            ele.RemoveAttr("uigs");
            ele.RemoveAttr("data-isv");
            ele.RemoveAttr("data-headimage");   //移除来自公众号
            ele.RemoveAttr("i");
            ele.RemoveAttr("id");
            ele.RemoveAttr("target");

            Elements li = result.Select("li");
            li.RemoveAttr("d");
            li.RemoveAttr("id");
            li.RemoveAttr("class");

            Elements span = result.Select("span");//移除链接下面无效的信息
            span.Remove();

            Elements cite = result.Select("s-p");
            cite.Remove();

            Elements style = result.Select("style");   //清空 script模板
            style.Remove();

            Elements script = result.Select("script");   //清空 script模板
            script.Remove();

            Elements nums = result.Select(".mun");  //计数的文字
            nums.Remove();
        }

        void InitParam()
        {
            if (!IsFristRun)
            {
                if (!IsCode_WX) return;    //未出现验证码
                if (IsExistsIntent()) BLL.SnapToken.GetByWeChat(SNUID);
            }

            IsFristRun = false;
            //出现验证码，获取最新的 SNUID 和 SUV
            try
            {
                Dictionary<string, object> dic = BLL.SnapToken.GetByWeChat();
                if (dic != null)
                {
                    SNUID = Convert.ToString(dic["SNUID"]);
                    SUID = Convert.ToString(dic["SUID"]);
                    SUV = Convert.ToString(dic["SUV"]);
                }
            }
            catch { }

            //记录次数
            dbCount++;
            if (dbCount >= 10)
            {
                Pigeon.Utility.Log.Write(string.Format("code{0}.log", DateTime.Now.ToString("yyyyMMdd")), string.Format("微信从数据库中拉取参数{0}次！", dbCount));
                dbCount = 0;
            }
        }



        [System.Runtime.InteropServices.DllImport("wininet.dll")]
        private extern static bool InternetGetConnectedState(int Description, int ReservedValue);
        bool IsExistsIntent()
        {
            return InternetGetConnectedState(0, 0);
        }
    }
}
